package com.example.sqliteviewer;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class DatabaseViewerActivity extends AppCompatActivity implements TableAdapter.OnTableClickListener {

    private String databasePath;
    private SQLiteDatabase database;
    private RecyclerView recyclerView;
    private TableAdapter adapter;
    private List<String> tableNames;
    private TextView emptyView;
    private TextView tvDatabaseInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_database_viewer);
        
        databasePath = getIntent().getStringExtra("DATABASE_PATH");
        if (databasePath == null) {
            Toast.makeText(this, "数据库路径无效", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        File dbFile = new File(databasePath);
        setTitle(dbFile.getName());
        
        recyclerView = findViewById(R.id.recyclerView);
        emptyView = findViewById(R.id.emptyView);
        tvDatabaseInfo = findViewById(R.id.tvDatabaseInfo);
        
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        tableNames = new ArrayList<>();
        adapter = new TableAdapter(this, tableNames, this);
        recyclerView.setAdapter(adapter);
        
        loadDatabaseInfo();
        loadTables();
    }
    
    private void loadDatabaseInfo() {
        File dbFile = new File(databasePath);
        StringBuilder info = new StringBuilder();
        info.append("文件名: ").append(dbFile.getName()).append("\n");
        info.append("路径: ").append(dbFile.getAbsolutePath()).append("\n");
        
        // 文件大小
        long fileSize = dbFile.length();
        String fileSizeStr;
        if (fileSize < 1024) {
            fileSizeStr = fileSize + " B";
        } else if (fileSize < 1024 * 1024) {
            fileSizeStr = String.format("%.2f KB", fileSize / 1024.0);
        } else {
            fileSizeStr = String.format("%.2f MB", fileSize / (1024.0 * 1024));
        }
        info.append("大小: ").append(fileSizeStr);
        
        tvDatabaseInfo.setText(info.toString());
    }
    
    private void loadTables() {
        tableNames.clear();
        
        try {
            database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READONLY);
            
            // 查询所有表名
            Cursor cursor = database.rawQuery(
                    "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE 'android_%'", 
                    null);
            
            if (cursor.moveToFirst()) {
                do {
                    String tableName = cursor.getString(0);
                    tableNames.add(tableName);
                } while (cursor.moveToNext());
                cursor.close();
            }
            
            // 更新UI
            adapter.notifyDataSetChanged();
            
            if (tableNames.isEmpty()) {
                recyclerView.setVisibility(View.GONE);
                emptyView.setVisibility(View.VISIBLE);
            } else {
                recyclerView.setVisibility(View.VISIBLE);
                emptyView.setVisibility(View.GONE);
            }
            
        } catch (Exception e) {
            Toast.makeText(this, "无法打开数据库: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    public void onTableClick(String tableName) {
        Intent intent = new Intent(this, TableViewerActivity.class);
        intent.putExtra("DATABASE_PATH", databasePath);
        intent.putExtra("TABLE_NAME", tableName);
        startActivity(intent);
    }
    
    private static final int CREATE_TABLE_REQUEST_CODE = 1001;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_database_viewer, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        
        if (id == R.id.action_execute_sql) {
            Intent intent = new Intent(this, QueryActivity.class);
            intent.putExtra("DATABASE_PATH", databasePath);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_import_csv) {
            Intent intent = new Intent(this, CsvImportActivity.class);
            intent.putExtra("DATABASE_PATH", databasePath);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_create_table) {
            Intent intent = new Intent(this, CreateTableActivity.class);
            intent.putExtra("DATABASE_PATH", databasePath);
            startActivityForResult(intent, CREATE_TABLE_REQUEST_CODE);
            return true;
        }
        
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CREATE_TABLE_REQUEST_CODE && resultCode == RESULT_OK) {
            // 刷新表格列表
            loadTables();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (database != null && database.isOpen()) {
            database.close();
        }
    }
}